import React, { useEffect } from "react";
import { Modal, Form, Input, Button, Select } from "antd";
import { Role } from "../../../../api/type/ckgl";
const { Option } = Select;
interface RenameModalProps {
  title: string;
  defaultValue?: any;
  visible: boolean;
  roles: Role[];
  onCancel: () => void;
  onOk: (values: any) => void;
}

const AddUserModal: React.FC<RenameModalProps> = ({
  title,
  defaultValue,
  visible,
  onCancel,
  onOk,
  roles = [],
}) => {
  const [form] = Form.useForm();

  useEffect(() => {
    form.resetFields();
  }, [visible, form]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      onOk(values);
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };

  return (
    <Modal
      title={title}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button key="ok" type="primary" onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form
        form={form}
        initialValues={{
          ...defaultValue,
        }}
      >
        <Form.Item
          label="用户名" // 设置标签文本
          name="username"
          rules={[
            {
              required: true,
              whitespace: true,
              message: "请输入用户名称",
            },
            { min: 2, message: "用户名最少需要4个字符" },
          ]}
          validateTrigger="onBlur"
        >
          <Input placeholder="请输入新名称" />
        </Form.Item>
        <Form.Item
          label="邮箱" // 设置标签文本
          name="email" // 将 name 更新为 "email"
          rules={[
            { required: true, message: "请输入邮箱", whitespace: true },
            { type: "email", message: "请输入有效的邮箱地址" }, // 可选：添加电子邮件验证规则
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item
          label="密码" // 设置标签文本
          name="password"
          rules={[{ required: true, message: "请输入密码", whitespace: true }]}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>
        <Form.Item
          label="用户角色"
          name="role_code"
          rules={[
            {
              required: true,
              message: "请选择用户角色",
            },
          ]}
        >
          <Select placeholder="请选择用户角色" allowClear>
            {roles.map((role) => (
              <Option key={role.code} value={role.code}>
                {role.name}
              </Option>
            ))}
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddUserModal;
